package com.comtime.login;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.comtime.smartbox.BaseActivity;
import com.comtime.smartkilimanjaro.R;
import com.comtime.utils.MD5Util;
import com.comtime.utils.MyConfig;
import com.comtime.utils.MySharedPreferences;
import com.comtime.utils.ToastUtils;
import com.comtime.utils.Util;
import com.comtime.view.MyDialog;
import com.comtime.view.MyProgressDialog;
import com.comyou.comyouhttp.ComyouHttpCallBack;
import com.comyou.comyouhttp.ComyouHttpClient;
import com.comyou.comyouhttp.ComyouHttpProgram;

public class RegistActivity extends BaseActivity implements OnClickListener {
    EditText edt_phone, edt_code, edt_pwd, edt_pwd_two;
    Button btn_next, btn_sure;
    TextView tv_get_code, tv_one_result, tv_two_result, tv_phone;
    LinearLayout line_one, line_two, line_get_code;

    CheckBox check_box;
    ImageView image_show_pwd, image_show_two_pwd;
    ImageView image_clear_pwd, image_clear_two_pwd;

    int xml_choice = 1;// 第几个xml

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist_password);
        init();
    }

    void init() {
        // xml one
        line_two = (LinearLayout) findViewById(R.id.line_two);
        edt_pwd = (EditText) findViewById(R.id.et_pwd);
        edt_pwd_two = (EditText) findViewById(R.id.et_again_pwd);
        edt_pwd.addTextChangedListener(mTextWatcher);
        edt_pwd_two.addTextChangedListener(mTextWatcher);
        tv_one_result = (TextView) findViewById(R.id.tv_one_result);

        image_show_pwd = (ImageView) findViewById(R.id.image_pwd_show);
        image_show_two_pwd = (ImageView) findViewById(R.id.image_again_pwd_show);

        image_show_pwd.setOnClickListener(this);
        image_show_two_pwd.setOnClickListener(this);

        image_clear_pwd = (ImageView) findViewById(R.id.image_pwd_delete);
        image_clear_two_pwd = (ImageView) findViewById(R.id.image_again_pwd_delete);

        image_clear_pwd.setOnClickListener(this);
        image_clear_two_pwd.setOnClickListener(this);


        check_box = (CheckBox) findViewById(R.id.image_check);
        btn_next = (Button) findViewById(R.id.bt_next);
        btn_next.setTextColor(getResources().getColor(R.color.item_white));
        btn_next.setBackgroundResource(R.drawable.bg_round_stroke_white_5dp);
        btn_next.setOnClickListener(this);

        // xml two
        line_one = (LinearLayout) findViewById(R.id.line_one);
        edt_phone = (EditText) findViewById(R.id.et_phone);
        //RZC Add
        edt_phone.addTextChangedListener(mTextWatcher);
        edt_code = (EditText) findViewById(R.id.et_auth_code);
        tv_get_code = (TextView) findViewById(R.id.tv_auth_code);
        tv_two_result = (TextView) findViewById(R.id.tv_two_result);
        tv_phone = (TextView) findViewById(R.id.tv_phonenum);

        line_get_code = (LinearLayout) findViewById(R.id.line_get_code);
        line_get_code.setOnClickListener(this);
        btn_sure = (Button) findViewById(R.id.bt_sure);
        btn_sure.setOnClickListener(this);

        handler.post(clearRunnable);

    }

    //RZC Add  添加内容改变监听，对错误提示信息进行隐藏
    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            if (tv_one_result.getVisibility() == View.VISIBLE)
                tv_one_result.setVisibility(View.INVISIBLE);
        }
    };

    /**
     * 返回键
     *
     * @param v
     */
    public void BackAction(View v) {
        this.finish();
        overridePendingTransition(R.anim.enter_left, R.anim.exit_right);
    }

    /**
     * 注册信息
     */
    public void RegistInfoAction(View v) {
        Intent intent = new Intent(this, RegistInfoActivity.class);
        startActivity(intent);
    }

    /**
     * 跳登录
     */
    public void LoginAction(View v) {
        this.finish();
        overridePendingTransition(R.anim.enter_left, R.anim.exit_right);
    }

    boolean show_pwd_flag = false;// 默认隐藏
    boolean show_again_pwd_flag = false;// 默认隐藏

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.image_pwd_show:
                // 显示密码

                show_pwd_flag = !show_pwd_flag;
                if (show_pwd_flag) {
                    // 显示密码
                    edt_pwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    image_show_pwd.setImageResource(R.drawable.icon_show);
                } else {
                    // 隐藏密码
                    edt_pwd.setInputType(InputType.TYPE_CLASS_TEXT
                            | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    image_show_pwd.setImageResource(R.drawable.icon_hide);
                }
                break;
            case R.id.image_again_pwd_show:
                // 显示密码
                show_again_pwd_flag = !show_again_pwd_flag;
                if (show_again_pwd_flag) {
                    // 显示密码
                    edt_pwd_two
                            .setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    image_show_two_pwd.setImageResource(R.drawable.icon_show);
                } else {
                    // 隐藏密码
                    edt_pwd_two.setInputType(InputType.TYPE_CLASS_TEXT
                            | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    image_show_two_pwd.setImageResource(R.drawable.icon_hide);
                }
                break;
            case R.id.image_pwd_delete:
                edt_pwd.setText("");
                break;
            case R.id.image_again_pwd_delete:
                edt_pwd_two.setText("");
                break;
            case R.id.line_get_code:
                // 获取验证码
                getCode();
                break;

            case R.id.bt_next:
                Log.e("tag", "next");
                next();
                break;
            case R.id.bt_sure:
                // sure
                sure();
                break;
            default:
                break;
        }
    }

    /**
     * 获取验证码
     */
    void getCode() {
        if (!Util.hasNetwork(RegistActivity.this)) {
            showTextOne(getString(R.string.no_network).toString(), false);
            return;
        }
        if (TextUtils.isEmpty(edt_phone.getText())) {

            showTextOne(getString(R.string.input_phone).toString(), false);
            return;
        }
        if (!Util.isMobileNO(edt_phone.getText().toString())) {

            showTextOne(getString(R.string.phone_format_wrong).toString(),
                    false);
            return;
        }
        line_get_code.setEnabled(false);
        num = 60;
        handler.post(runnable);
        phoneNum = edt_phone.getText().toString();
        final MyProgressDialog progressDialog = new MyProgressDialog(
                RegistActivity.this);
        progressDialog.setContent(getString(R.string.getting).toString());
        progressDialog.show();
        ComyouHttpProgram httpProgram = new ComyouHttpProgram();
        httpProgram.add("targetPhoneNum", phoneNum);
        httpProgram.add("type", 1 + "");
        ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
                + "app/getauthcode");
        httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

            @Override
            public void onResponse(String reString) {
                progressDialog.dismiss();
                Log.e("RZC registerdcode", reString);
                try {
                    JSONObject jsonObject = new JSONObject(reString);
                    int status = jsonObject.getInt("err");
                    if (status == 0) {
                        handler.sendEmptyMessage(1);

                    } else {
                        num = -1;
                        handler.sendEmptyMessage(2);
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(String arg0, IOException arg1) {
                progressDialog.dismiss();
                num = -1;
                handler.sendEmptyMessage(2);
            }

        });
    }

    /**
     * next
     */
    String phoneNum = "", code = "", pwd = "";

    void next() {
        if (!Util.hasNetwork(RegistActivity.this)) {
            showTextOne(getString(R.string.no_network).toString(), false);
            return;
        }
        if (TextUtils.isEmpty(edt_phone.getText())) {

            showTextOne(getString(R.string.input_phone).toString(), false);
            return;
        }
        if (!Util.isMobileNO(edt_phone.getText().toString())) {

            showTextOne(getString(R.string.phone_format_wrong).toString(),
                    false);
            return;
        }
        String pwd_one = edt_pwd.getText().toString();
        String pwd_two = edt_pwd_two.getText().toString();
        if (pwd_one.length() < 6 || pwd_two.length() < 6) {
            showTextTwo(getString(R.string.pwd_short).toString(), false);
            return;
        }
        if (pwd_one.length() > 20 || pwd_two.length() > 20) {
            showTextOne(getString(R.string.pwd_more).toString(), false);
            return;
        }

        if (!pwd_one.equals(pwd_two)) {
            showTextOne(getString(R.string.pwd_un_same).toString(), false);
            return;
        }

        if (!check_box.isChecked()) {
            showTextOne(getString(R.string.can_next).toString(), false);
            return;
        }
        phoneNum = edt_phone.getText().toString();

        xml_choice = 2;
        pwd = edt_pwd.getText().toString();
        line_one.setVisibility(View.GONE);
        line_two.setVisibility(View.VISIBLE);

        tv_phone.setText(phoneNum.subSequence(0, 3) + "****" + phoneNum.substring(7));
    }

    /**
     * set pwd
     */
    void sure() {
        if (!Util.hasNetwork(RegistActivity.this)) {
            showTextTwo(getString(R.string.no_network).toString(), false);
            return;
        }
        if (TextUtils.isEmpty(edt_pwd.getText())) {

            showTextTwo(getString(R.string.pwd_hint).toString(), false);
            return;
        }
        if (TextUtils.isEmpty(edt_pwd_two.getText())) {
            showTextTwo(getString(R.string.pwd_hint).toString(), false);
            return;
        }
        if (TextUtils.isEmpty(edt_code.getText())
                || edt_code.getText().toString().length() < 6) {

            showTextOne(getString(R.string.import_auth).toString(), false);
            return;
        }
        code = edt_code.getText().toString();

        final MyProgressDialog progressDialog = new MyProgressDialog(
                RegistActivity.this);
        progressDialog.setContent(getString(R.string.getting).toString());
        progressDialog.show();
        ComyouHttpProgram httpProgram = new ComyouHttpProgram();
        httpProgram.add("phoneNum", phoneNum);
        httpProgram.add("pwd", MD5Util.md5(pwd));
        httpProgram.add("authcode", code);
        ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
                + "app/register");
        httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

            @Override
            public void onResponse(String reString) {
                progressDialog.dismiss();
                Log.e("tag", reString);
                try {
                    JSONObject jsonObject = new JSONObject(reString);
                    int status = jsonObject.getInt("err");
                    if (status == 0) {
                        //handler.sendEmptyMessage(3);
                        Message message = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("phone", phoneNum);
                        bundle.putString("pwd",pwd);
                        Log.e("BUNDLE", "P :" + phoneNum);
                        message.setData(bundle);
                        message.what = 3;
                        handler.sendMessage(message);


                    } else {
                        // 0 成功 1：缺少参数 2：手机号码已被注册 3：验证码不正确 4：验证码过期
                        num = -1;
                        final String str;
                        switch (status) {
                            case 2:
                                str = getText(R.string.phone_has_regist).toString();
                                break;
                            case 3:
                                str = getText(R.string.code_wrong).toString();
                                break;
                            case 4:
                                str = getText(R.string.code_data_more)
                                        .toString();
                                break;

                            default:
                                str = getText(R.string.regist_fail).toString();
                                break;
                        }

                        handler.post(new Runnable() {

                            @Override
                            public void run() {
                                ToastUtils.showToast(RegistActivity.this, str, 1500);

                            }
                        });
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String arg0, IOException arg1) {
                progressDialog.dismiss();
                num = -1;

            }
        });
    }

    /**
     * 自定义提示
     *
     * @param str
     */
    Toast toast = null;

    void showToast(String str) {
        if (toast != null) {
            toast.cancel();
        }
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.toastshow, null);
        TextView textView = (TextView) view.findViewById(R.id.toastshow);
        textView.setText(str);
        toast = new Toast(this);
        double d = getResources().getDisplayMetrics().density;
        toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.CENTER, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(view);
        toast.show();
    }

    void showTextOne(String str, boolean erroy) {
        tv_one_result.setText(str);
        tv_one_result.setVisibility(View.VISIBLE);
        if (erroy) {
            tv_one_result.setTextColor(getResources().getColor(
                    R.color.item_white));
        } else {
            tv_one_result.setTextColor(getResources().getColor(
                    R.color.item_orange));
        }
    }

    void showTextTwo(String str, boolean erroy) {
        tv_two_result.setText(str);
        tv_two_result.setVisibility(View.VISIBLE);
        if (erroy) {
            tv_two_result.setTextColor(getResources().getColor(
                    R.color.item_white));
        } else {
            tv_two_result.setTextColor(getResources().getColor(
                    R.color.item_orange));
        }
    }

    Handler handler = new Handler() {
        public void handleMessage(final android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    // 获取验证码成功

                    String str = String.format(getString(R.string.code_success)
                            .toString(), phoneNum);

                    showTextTwo(str, true);

                    break;
                case 2:
                    // 获取验证码失败

                    showTextTwo(getString(R.string.code_fail).toString(), true);
                    break;
                case 3:
                    // 注册成功
                    final String num = msg.getData().getString("phone");
                    final String pwd = msg.getData().getString("pwd");
                    Log.e("RZCNUM", "num=" + num);

                    handler.postDelayed(new Runnable() {

                        @Override
                        public void run() {

                            RegistActivity.this.finish();
                            Intent intent = new Intent(RegistActivity.this, LoginActivity.class);
                            intent.putExtra("phone", num);
                            intent.putExtra("pwd",pwd);
                            startActivity(intent);
                            showToast(getString(R.string.regist_success).toString());
                            overridePendingTransition(R.anim.enter_left,
                                    R.anim.exit_right);


                        }
                    }, 1000);
                    break;
                case 4:
                    // 注册失败
                    String str_fail = (String) msg.obj;
                    showTextTwo(str_fail, false);
                    break;

                default:
                    break;
            }
        }

        ;
    };

    /**
     * 60s倒计时
     */
    int num = 60;
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub

            if (num >= 0) {

                tv_get_code.setText(num + "s");

                num--;
                handler.postDelayed(this, 1000);
            } else {
                num = 60;
                line_get_code.setEnabled(true);
                tv_get_code.setText(getString(R.string.reset_code).toString());
            }

        }
    };


    /**
     * 显示或隐藏删除图片
     *
     * @param str
     */

    Runnable clearRunnable = new Runnable() {

        @Override
        public void run() {
            if (xml_choice == 1) {
                if (TextUtils.isEmpty(edt_pwd.getText())) {
                    image_clear_pwd.setVisibility(View.INVISIBLE);
                } else {
                    image_clear_pwd.setVisibility(View.VISIBLE);
                }
                if (TextUtils.isEmpty(edt_pwd_two.getText())) {
                    image_clear_two_pwd.setVisibility(View.INVISIBLE);
                } else {
                    image_clear_two_pwd.setVisibility(View.VISIBLE);
                }
                //RZC  注册时下一步按钮一直能够点击，点击后再去判断手机号和密码格式。
                /*if(edt_phone.getText().toString().length()==11&&edt_pwd.getText().toString().length()>=6&&edt_pwd_two.getText().toString().length()>=6){
					btn_next.setEnabled(true);
					btn_next.setTextColor(getResources().getColor(R.color.item_white));
					btn_next.setBackgroundResource(R.drawable.bg_round_stroke_white_5dp);
				}else{
					btn_next.setEnabled(false);
					btn_next.setTextColor(getResources().getColor(R.color.item_gray));
					btn_next.setBackgroundResource(R.drawable.bg_round_stroke_gray_5dp);
				}*/
            } else {

                if (!TextUtils.isEmpty(edt_code.getText())) {
                    btn_sure.setEnabled(true);
                    btn_sure.setTextColor(getResources().getColor(R.color.item_white));
                    btn_sure.setBackgroundResource(R.drawable.bg_round_stroke_white_5dp);
                } else {
                    btn_sure.setEnabled(false);
                    btn_sure.setTextColor(getResources().getColor(R.color.item_gray));
                    btn_sure.setBackgroundResource(R.drawable.bg_round_stroke_gray_5dp);
                }


            }
            handler.postDelayed(clearRunnable, 500);
        }
    };

    void showSucessDialog(String str) {
        final MyDialog myDialog = new MyDialog(RegistActivity.this);
        myDialog.setContent(str);
        myDialog.getLeftButton().setText(getString(R.string.ok));
        myDialog.getLeftButton().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                myDialog.dismiss();
                RegistActivity.this.finish();
                overridePendingTransition(R.anim.enter_left, R.anim.exit_right);
            }
        });
        myDialog.show();
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();

        overridePendingTransition(R.anim.enter_left, R.anim.exit_right);
    }

}
